import _thread

import network
import ntptime
import uos as os
import utime as time
from machine import Timer, reset

from MsgProcess import MsgProcess


#万能开关控制中心
class zimeios(MsgProcess):
    def __init__(self):
        super().__init__()
        self.sta_if = None
        self.mymqtt = None
        self.is_synctime = False
        self.PluginPath = r'plugin'
        self.receive_func = []
        self.mqtttimer = Timer(-1)
        self.nettimer = Timer(-1)

    def reboot(self, e):
        reset()

    def read_wificonfig(self):
        file = self.config['wificonf']
        file_cont = ''
        try:
            os.stat(file)
            with open(file,'r') as f:
                file_cont = f.read()
        except OSError:pass
        return file_cont.strip()

    def read_equipm(self):
        file = self.config['equipm']
        try:
            file_cont = ''
            os.stat(file)
            with open(file,'r') as f:
                file_cont = f.read()
            return file_cont.strip()
        except OSError:
            return False

    def is_net(self):
        time_i = 0
        if not self.sta_if:
            self.sta_if = network.WLAN(network.STA_IF)
        is_net = True
        while not self.sta_if.isconnected():
            time.sleep(1)
            time_i += 1
            if time_i > 5:
                is_net = False
                break
        return bool(is_net)

    # 开始热点配网
    def start_ap_network(self):
        from setnetwork import Setnetwork
        self.nettimer.deinit()
        setnet = Setnetwork(self.config)
        setnet.main()

    # 开始网络连接
    def start_network(self):
        if (self.sta_if and self.sta_if.isconnected()):
            return 'yes'
        self.sta_if = network.WLAN(network.STA_IF)
        if not self.sta_if.active():self.sta_if.active(True)
        wifi_conf = self.read_wificonfig()
        if len(wifi_conf)>0:
            file_arr = wifi_conf.split('\n')
            if len(file_arr)>0:
                self.sta_if.connect(file_arr[0],file_arr[1])
                return 'yesconf'

        print("设备还没有初始化配置,请打开【自美系统】微信小程序,使用:设备控制=>万能开关=>添加设备,初始化此设备。")
        self.start_ap_network()
        return 'noinit'

    def mqtt_receive(self, topic, rejson):
        for func in self.receive_func:
            func(rejson)

    # 开始 MQTT 连接
    def start_mqtt(self):
        from mqttclient import Mqttclient
        self.mymqtt = Mqttclient(self.config)
        self.mymqtt.receive = self.mqtt_receive
        return self.mymqtt.main()

    def LoadPlugin(self, pluginName):
        package = f'plugin.{pluginName}'
        try:
            process = getattr(getattr(__import__(package), pluginName), pluginName)
            process.send = self.mymqtt.send
            pluginobj = process()
            if pluginobj.Text not in self.receive_func:
                self.receive_func.append(pluginobj.Text)
            # pluginobj.Start()
            _thread.start_new_thread(pluginobj.Start,())
            del package
        except Exception as e:
            print(f'插件[{pluginName}]模块加载失败! {repr(e)}')
            return

    def SyncTime(self):
        ntptime.NTP_DELTA = 3155644800      # 时差
        ntptime.host = 'ntp1.aliyun.com'    # 阿里云时间服务器
        while not self.is_synctime:
            try:
                ntptime.settime()
                print(time.localtime())
                self.is_synctime = True
            except Exception as e:
                print(f'同步时间超时:{e}')
            time.sleep(1)

    def init(self):
        if self.start_mqtt():
            plugin_path = os.listdir(self.PluginPath)
            for item in plugin_path:
                plugin = item.split('.')[0]
                if plugin != '__init__' and self.is_filetype(f'{self.PluginPath}/{item}')=='file':
                    self.LoadPlugin(plugin)
        else:
            self.mqtttimer.init(period=15000, mode=Timer.ONE_SHOT, callback=self.reboot)
            print("尝试连接到消息通讯服务失败!")
        self.SyncTime()

    def init_keynetwork(self):
        from zmkeys import zmkeys
        zmkeys(self.config['gpio']['setnetpin'], self.start_ap_network).keyParaInit()

    def main(self):
        self.init_keynetwork()
        confst = self.start_network()
        if self.is_net():
            self.init()
        elif confst=='yesconf':
            print('Network connection failed')
            self.nettimer.init(period=30000, mode=Timer.ONE_SHOT, callback=self.reboot)
